package cn.appsys.controller;

import cn.appsys.pojo.*;
import cn.appsys.service.*;
import lombok.extern.log4j.Log4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j
@Controller
@RequestMapping("/dev")
public class DevUserController {
    @Autowired
    private DevUserService devUserService;
    @Autowired
    private BackendUserService backendUserService;
    @Autowired
    private AppInfoService appinfoService;
    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Autowired
    private AppCategoryService appCategoryService;
    @Autowired
    private AppversionService appversionService;

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpSession session, @RequestParam(required = false) String devCode, @RequestParam(required = false) String devPassword) {
        log.debug("开发者登录");
        DevUser user = this.devUserService.getLoginUser(devCode);
        if (user != null) {
            if (user.getDevPassword().equals(devPassword)) {
                session.setAttribute("devSession", user);
                log.debug("跳转到开发者首页");
                return "developer/main";
            } else {
                request.setAttribute("message", "密码错误");
                log.debug("跳转到开发者登录页面");
                return "devlogin";
            }
        } else {
            request.setAttribute("message", "账号不存在");
            log.debug("跳转到开发者登录页面");
            return "devlogin";
        }
    }

    @RequestMapping("/toLogin")
    public String login() {
        log.debug("跳转到开发者登录页面");
        return "devlogin";
    }



    @RequestMapping("/devviewAppInfoList")
    public String viewAppInfoList(Model model, HttpSession session,
                                  @RequestParam(required = false, defaultValue = "") String devSoftwareName,
                                  @RequestParam(required = false, defaultValue = "0") Integer devFlatformId,
                                  @RequestParam(required = false, defaultValue = "0") Integer devStatus,
                                  @RequestParam(required = false, defaultValue = "0") Integer categoryLevel1,
                                  @RequestParam(required = false, defaultValue = "0") Integer categoryLevel2,
                                  @RequestParam(required = false, defaultValue = "0") Integer categoryLevel3,
                                  @RequestParam(required = false, defaultValue = "1") Integer currPageNo) {
        session.setAttribute("softwareName", devSoftwareName);
        session.setAttribute("flatformId", devFlatformId);
        session.setAttribute("devStatus", devStatus);
        session.setAttribute("categoryLevel1", categoryLevel1);
        session.setAttribute("categoryLevel2", categoryLevel2);
        session.setAttribute("categoryLevel3", categoryLevel3);
        Page page = new Page();
        //页大小
        page.setPageSize(5);
        //当前页
        page.setCurrPageNo(currPageNo);
        page.setTotalCount(dataDictionaryService.getDevAppInfoListCout(devSoftwareName, devStatus, devFlatformId, categoryLevel1, categoryLevel2, categoryLevel3));
        page.setList(dataDictionaryService.getDevAppInfoList(devSoftwareName, devStatus, devFlatformId, categoryLevel1, categoryLevel2, categoryLevel3, page));
        if (page.getCurrPageNo() <= 0) {
            page.setCurrPageNo(1);
        }
        model.addAttribute("currPageNo", currPageNo);
        model.addAttribute("appInfoList", page.getList());
        model.addAttribute("page", page);
        return "developer/appinfolist";
    }

    @RequestMapping("devcategoryLevel1")
    public String devcategoryLevel1(Model model, @RequestParam(required = false) Integer selectId) {
        List<AppCategory> ca1 = appCategoryService.getCategoryLevel1();
        model.addAttribute("listcategoryLevel1", ca1);
        return "fenlei/yiji";
    }

    @RequestMapping("devcategoryLevel2")
    public String devcategoryLevel2(Model model, @RequestParam Integer parentId2, @RequestParam(required = false) Integer selectId) {
        List<AppCategory> ca2 = appCategoryService.getCategoryLevel2(parentId2);
        model.addAttribute("listcategoryLevel2", ca2);
        return "fenlei/erji";
    }

    @RequestMapping("devcategoryLevel3")
    public String devcategoryLevel3(Model model, @RequestParam Integer parentId3, @RequestParam(required = false) Integer selectId) {
        List<AppCategory> ca3 = appCategoryService.getCategoryLevel3(parentId3);
        model.addAttribute("listcategoryLevel3", ca3);
        return "fenlei/sanji";
    }

    @RequestMapping("devpingtaiName")
    public String devpingtaiName(Model model, HttpSession session, @RequestParam(required = false) Integer selectId) {
        //平台属性
        List<DataDictionary> terraceProperty = dataDictionaryService.getPintai();
        model.addAttribute("terraceProperty", terraceProperty);
        return "fenlei/pingtai";
    }

    @RequestMapping("zhuangtai")
    public String zhuangtai(Model model) {
        //状态属性
        List<DataDictionary> statusProperty = dataDictionaryService.getStatus();
        model.addAttribute("statusProperty", statusProperty);
        return "fenlei/status";
    }

    @RequestMapping("devxinzeng")
    public String devxinzeng(HttpSession session) {
        session.removeAttribute("categoryLevel1");
        session.removeAttribute("softwareName");
        session.removeAttribute("categoryLevel2");
        session.removeAttribute("categoryLevel3");
        session.removeAttribute("devStatus");
        session.removeAttribute("flatformId");
        return "developer/appinfoadd";
    }

    @RequestMapping("apkmingcheng")
    @ResponseBody
    public String apkmingcheng(@RequestParam String apk) {
        int data = appinfoService.selectApkNameCount(apk);
        if ("".equals(apk) || null == apk) {
            return "{\"flag\":\"empty\"}";
        } else if (data > 0) {
            return "{\"flag\":\"true\"}";
        } else {
            return "{\"flag\":\"false\"}";
        }
    }

    @RequestMapping("devupdatelist")
    public String devupdatelist(@RequestParam Integer AppInfoId, Model model, HttpSession session) {
        AppInfo appInfo = appinfoService.getAppInfoView(AppInfoId);
        model.addAttribute("appInfo", appInfo);
        session.setAttribute("categoryLevel1", appInfo.getCategoryLevel1());
        session.setAttribute("categoryLevel2", appInfo.getCategoryLevel2());
        session.setAttribute("categoryLevel3", appInfo.getCategoryLevel3());
        session.setAttribute("flatformId", appInfo.getFlatformId());
        return "developer/appinfomodify";
    }

    @PostMapping("devadd")
    public String dev(AppInfo appInfo, HttpSession session, HttpServletRequest request, @RequestParam(value = "idPicPath", required = false) MultipartFile idPicPath) {
        String idPic = null;
        String opr = request.getParameter("opr");
        String loPic = null;
        String tiaozhuan = "";
        if("0".equals(opr)){
            tiaozhuan="redirect:/dev/appinfoadd";
        }else{
            tiaozhuan="redirect:/dev/devxinzeng";
        }
        if (idPicPath != null) {
            String originalFilename = idPicPath.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(originalFilename);
            int filesize = 500000;
            if (idPicPath.getSize() > filesize) {
                request.setAttribute("uploadsession", "文件上传大小不能超过500kb");
                return tiaozhuan;
            } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("pbg")) {
                String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                File targetFile = new File("D:\\upload");
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    idPicPath.transferTo(new File(targetFile, fileName));
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("uploadsession", "上传失败");
                    return tiaozhuan;
                }
                idPic = File.separator + "upload" + File.separator + fileName;
                loPic = "D:" + File.separator + "upload" + File.separator + fileName;

            } else {
                request.setAttribute("uploadsession", "上传图片格式不正确");
                return tiaozhuan;
            }

            if ("0".equals(opr)) {
                appInfo.setDevId(((DevUser) session.getAttribute("devSession")).getId());
                appInfo.setCreatedBy(((DevUser) session.getAttribute("devSession")).getId());
                appInfo.setCreationDate(new Date());
                appInfo.setLogoPicPath(idPic);
                appInfo.setLogoLocPath(loPic);
                if (appinfoService.addAppInfo(appInfo) > 0) {
                    tiaozhuan = "redirect:/dev/devviewAppInfoList";
                } else {
                    tiaozhuan = "redirect:/dev/devxinzeng";
                }
            } else if ("1".equals(opr)) {
                appInfo.setDevId(((DevUser) session.getAttribute("devSession")).getId());
                appInfo.setModifyBy(((DevUser) session.getAttribute("devSession")).getId());
                appInfo.setModifyDate(new Date());
                appInfo.setLogoPicPath(idPic);
                appInfo.setLogoLocPath(loPic);
                if (appinfoService.doAppUpdate(appInfo) > 0) {
                    session.removeAttribute("categoryLevel1");
                    session.removeAttribute("softwareName");
                    session.removeAttribute("categoryLevel2");
                    session.removeAttribute("categoryLevel3");
                    session.removeAttribute("devStatus");
                    tiaozhuan = "redirect:/dev/devviewAppInfoList";
                } else {
                    tiaozhuan = "redirect:/dev/devupdatelist";
                }
            }
        }
        return tiaozhuan;
    }

    @ResponseBody
    @RequestMapping("tupiandelete")
    public Object tupiandelete(@RequestParam Integer id) {
        Map<String, Object> map = new HashMap();
        AppInfo appInfo=appinfoService.getAppInfoView(id);
        if (appInfo.getLogoLocPath()!=null) {
            File file = new File(appInfo.getLogoLocPath());
            file.delete();
            int data = appinfoService.updateFile(id);
            if(data>0){
                map.put("flag", "true");
            }else{
                map.put("flag","bucunzai");
            }
        }
        return map;
    }
    @ResponseBody
    @RequestMapping("apkdelete")
    public Object apkdelete(@RequestParam Integer id) {
        Map<String, Object> map = new HashMap();
        Appversion appversion=appversionService.getbanbenId(id);
        if (appversion.getApkLocPath()!=null) {
            File file = new File(appversion.getApkLocPath());
            file.delete();
            int data = appversionService.updateFile(id);
            if(data>0){
                map.put("flag", "true");
            }else{
                map.put("flag","bucunzai");
            }
        }
        return map;
    }
    @RequestMapping("banbenadd")
    public String banbenadd(Model model,@RequestParam Integer appid){
        List<Appversion> list=appversionService.getbanben(appid);
        model.addAttribute("appId",appid);
        model.addAttribute("list",list);
        return "developer/appbanbenadd";
    }
    @RequestMapping("banbenmodify")
    public String banbenmodify(Model model,@RequestParam Integer appid,@RequestParam Integer versionid){
        List<Appversion> list=appversionService.getbanben(appid);
        Appversion appversion=appversionService.getbanbenId(versionid);
        model.addAttribute("appVersion",appversion);
        model.addAttribute("list",list);
        return "developer/appbanbenmodify";
    }
    @ResponseBody
    @RequestMapping("shangjia")
    public Object shangjia(@RequestParam Integer id,@RequestParam Integer status){
        Map<String,Object> map=new HashMap();
        int data=appinfoService.putawayApp(id, status);
        if(data>0){
            map.put("flag","true");
        }else{
            map.put("flag","false");
        }
        return map;
    }
    @RequestMapping("addversionsave")
    public String addVersionSave(Appversion appversion,HttpSession session,HttpServletRequest request,
                                 @RequestParam(value = "a_downloadLink",required = false) MultipartFile attach){
        String downloadLink=null;
        String apkLoPath=null;
        String apkFileName=null;
        String status=request.getParameter("status");
        int data=0;
        String opr=request.getParameter("versionsave");
        String flag="";
        if("0".equals(opr)){
            flag="redirect:/dev/banbenadd";
        }else if ("1".equals(opr)){
            flag="redirect:/dev/banbenmodify";
        }
        if(!attach.isEmpty()){
            String path=request.getSession().getServletContext().getRealPath("statics"+File.separator+"upload");
            log.debug("uploadFile"+path);
            String oldFileName =attach.getOriginalFilename();
            String prefix=FilenameUtils.getExtension(oldFileName);
            if(prefix.equalsIgnoreCase("apk")){
                String apkName=null;
                try{
                     apkName=appinfoService.getAppInfoView(appversion.getAppId()).getApkName();
                }catch (Exception e){
                    e.printStackTrace();
                }
                apkFileName=apkName+"-"+appversion.getVersionNo()+".apk";
                File targetFile = new File("D:\\upload");
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                try{
                    attach.transferTo(new File(targetFile, apkFileName));
                }catch(Exception e){
                    e.printStackTrace();
                    return flag;
                }
                downloadLink=File.separator + "upload" + File.separator+apkFileName;
                apkLoPath="D:" + File.separator + "upload" + File.separator +apkFileName;
            }else{
                return flag;
            }
        }if ("0".equals(opr)) {
            appversion.setAppId(Integer.parseInt(request.getParameter("appId")));
            appversion.setApkLocPath(apkLoPath);
            appversion.setDownloadLink(downloadLink);
            appversion.setApkFileName(apkFileName);
            appversion.setCreatedBy(((DevUser) session.getAttribute("devSession")).getId());
            appversion.setCreationDate(new Date());
            data=appversionService.addbanben(appversion);

        } else if ("1".equals(opr)) {
            appversion.setApkLocPath(apkLoPath);
            appversion.setDownloadLink(downloadLink);
            appversion.setModifyBy(((DevUser) session.getAttribute("devSession")).getId());
            appversion.setModifyDate(new Date());
            data=appversionService.modifybanben(appversion);
            if("1".equals(status)){
                appinfoService.checkApp(1,appversion.getAppId());
            }
        }
        if(data>0) {
            int appupdateversion=appinfoService.updateAppVersion(appversion.getAppId(),appversion.getId());
            if(appupdateversion>0) {
                return "redirect:/dev/devviewAppInfoList";
            }else{
                return flag;
            }
        }else{
            return "developer/appbanbenadd";
        }
    }
    @RequestMapping("appchakan")
    public String chakan(Model model,@RequestParam Integer appid){
        AppInfo appInfo=appinfoService.getAppInfoView(appid);
        List<Appversion> list=appversionService.getbanben(appid);
        model.addAttribute("appId",appid);
        model.addAttribute("appInfo",appInfo);
        model.addAttribute("list",list);
        return "developer/appchakan";
    }
    @RequestMapping("appdel")
    @ResponseBody
    public String appdel(@RequestParam Integer appid){
        int count=appversionService.getdelCount(appid);
        int appstatus=0;
        int data=0;
        if(count>0){
            List<Appversion> appversion=appversionService.selectAppver(appid);
            for(Appversion appver:appversion) {
                if (appver.getApkLocPath() != null) {
                    File file = new File(appver.getApkLocPath());
                    file.delete();
                    data = appversionService.delete(appid);
                }
            }
            if(data>0){
                AppInfo appInfo=appinfoService.getAppInfoView(appid);
                if (appInfo.getLogoLocPath()!=null) {
                    File file = new File(appInfo.getLogoLocPath());
                    file.delete();
                    appstatus = appinfoService.delAppInfo(appid);
                    if (appstatus > 0) {
                        return "{\"flag\":\"true\"}";
                    }
                }
            }
        }else{
            AppInfo appInfo=appinfoService.getAppInfoView(appid);
            if (appInfo.getLogoLocPath()!=null) {
                File file = new File(appInfo.getLogoLocPath());
                file.delete();
                appstatus = appinfoService.delAppInfo(appid);
                if (appstatus > 0) {
                    return "{\"flag\":\"true\"}";
                }
            }
        }
        return "{\"flag\":\"false\"}";
    }

}
